import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class ComLivePlayer extends StatefulWidget {
  const ComLivePlayer({super.key});

  @override
  State<ComLivePlayer> createState() => _ComLivePlayerState();
}

class _ComLivePlayerState extends State<ComLivePlayer> {
  final String flvUrl = "http://localhost:8000/live/stream.flv";
  late WebViewController controller;
  final htmlContent = '''
    <!DOCTYPE html>
<html>
  <head>
    <title>FLPlayer</title>
    <script src="https://unpkg.com/flv.js/dist/flv.min.js"></script>
  </head>
  <body>
    <video id="videoElement" controls width="800" height="450"></video>

    <script>
      if (flvjs.isSupported()) {
        var videoElement = document.getElementById("videoElement");
        var flvPlayer = flvjs.createPlayer({
          type: "flv",
          url: "http://localhost:8000/live/stream.flv",
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
      }
    </script>
  </body>
</html>

    ''';

  @override
  void dispose() {
    controller.clearCache();
    controller.clearLocalStorage();
    super.dispose();
  }

  @override
  void initState() {
    controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (progress) {
                print("加载$progress");
              },
              onPageStarted: (url) {},
              onPageFinished: (url) {},
              onHttpError: (error) {},
              onWebResourceError: (error) {},
              onNavigationRequest: (request) {
                return NavigationDecision.navigate;
              },
            ),
          )
          ..loadHtmlString(htmlContent);
    // ..loadRequest(Uri.parse('https://www.bilibili.com/'));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("FLV直播")),
      body: WebViewWidget(controller: controller),
    );
  }
}
